package com.quectel.core.module.prewarning.service.impl;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.PreWarnConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.car.service.CarService;
import com.quectel.core.module.car.service.mongo.MongoCarAccessRecordService;
import com.quectel.core.module.entranceguard.service.mongo.MongoPersonAccessRecordService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.prewarning.dao.PreWarningRecordDao;
import com.quectel.core.module.prewarning.dto.PreWarningConfigDto;
import com.quectel.core.module.prewarning.dto.PreWarningRecordDto;
import com.quectel.core.module.prewarning.dto.PreWarningRecordHistoryDto;
import com.quectel.core.module.prewarning.entity.PreWarningRecordEntity;
import com.quectel.core.module.prewarning.service.PreWarningConfigService;
import com.quectel.core.module.prewarning.service.PreWarningRecordHistoryService;
import com.quectel.core.module.prewarning.service.PreWarningRecordService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2021-11-30 15:15:56
 */
@DubboService
public class PreWarningRecordServiceImpl implements PreWarningRecordService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PreWarningRecordServiceImpl.class);

    private static final String PRE_WARNING_RECORD_CACHE_BY_ID = RedisCacheConstants.PROJECT_NAME + "PRE_WARNING_RECORD_CACHE_BY_ID:";

    @Autowired
    private PreWarningRecordDao preWarningRecordDao;
    @Autowired
    private CarService carService;
    @Autowired
    private HouseholdService householdService;
    @Autowired
    private VillageService villageService;
    @Autowired
    private PreWarningConfigService preWarningConfigService;
    @Autowired
    private MongoCarAccessRecordService carAccessRecordService;
    @Autowired
    private PreWarningRecordService preWarningRecordService;
    @Autowired
    private MongoPersonAccessRecordService personAccessRecordService;
    @Autowired
    private PreWarningRecordHistoryService preWarningRecordHistoryService;

    @Override
    @Transactional
    public void clean(Long id) {
        PreWarningRecordDto preWarningRecordDto = selectById(id);
        if (Objects.nonNull(preWarningRecordDto)) {
            deleteById(id);

            PreWarningRecordHistoryDto preWarningRecordHistoryDto = CopyUtils.copyObj(preWarningRecordDto, PreWarningRecordHistoryDto.class);
            preWarningRecordHistoryService.save(preWarningRecordHistoryDto);
        }
    }

    @Override
    public PreWarningRecordDto selectOneByCar(Long villageId, Byte licenseColor, String license) {
        PreWarningRecordEntity entity = preWarningRecordDao.selectOne(
                new LambdaQueryWrapper<PreWarningRecordEntity>()
                        .eq(PreWarningRecordEntity::getVillageId, villageId)
                        .eq(PreWarningRecordEntity::getLicenseColor, licenseColor)
                        .eq(PreWarningRecordEntity::getLicense, license)
                        .last(SqlConstants.MYSQL_LIMIT_ONE)
        );
        return paddingField(CopyUtils.copyObj(entity, PreWarningRecordDto.class));
    }

    @Override
    public PreWarningRecordDto selectOne(Long objId, Byte type) {
        PreWarningRecordEntity entity = preWarningRecordDao.selectOne(
                new LambdaQueryWrapper<PreWarningRecordEntity>()
                        .eq(PreWarningRecordEntity::getObjId, objId)
                        .eq(PreWarningRecordEntity::getPreWarnType, type)
                        .last(SqlConstants.MYSQL_LIMIT_ONE)
        );
        return paddingField(CopyUtils.copyObj(entity, PreWarningRecordDto.class));
    }

    @Override
    public PreWarningRecordDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PRE_WARNING_RECORD_CACHE_BY_ID + id,

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PreWarningRecordDto selectById(Long id) {
        PreWarningRecordEntity entity = preWarningRecordDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, PreWarningRecordDto.class));
    }

    @Override
    public List<PreWarningRecordDto> queryList(Map<String, Object> params) {
        List<PreWarningRecordEntity> list = preWarningRecordDao.queryList(params);
        List<PreWarningRecordDto> result = CopyUtils.copyList(list, PreWarningRecordDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private PreWarningRecordDto paddingField(PreWarningRecordDto dto) {
        if (dto != null) {
            final Date currentDate = new Date();
            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            dto.setVillage(villageDto);

            if (StringUtils.isNotBlank(dto.getConfigBak())) {
                dto.setWarnConfigName(JacksonUtils.parse(dto.getConfigBak(), PreWarningConfigDto.class).getName());
            }

            if (PreWarnConstants.AlarmTypeEnum.CAR_RECORD_TOO_MANY.getType().equals(dto.getPreWarnType())) {
                dto.setDiffValue(dto.getFrequency() + "次");

                dto.setWarnDesc(String.format("车牌号'%s'触发了频繁出入预警，出入了%s", dto.getLicense(), dto.getDiffValue()));
            } else if (PreWarnConstants.AlarmTypeEnum.LONG_OUT_NO_IN.getType().equals(dto.getPreWarnType())
                    || PreWarnConstants.AlarmTypeEnum.LONG_IN_NO_OUT.getType().equals(dto.getPreWarnType())) {

                long durationMinutes = DateUtil.between(dto.getLastAccessTime(), currentDate, DateUnit.MINUTE, Boolean.TRUE);
                int hour = (int) (durationMinutes / 60);
                dto.setDiffValue(hour > 24 ? String.format("%s天%s小时%s分钟", hour / 24, hour % 24, durationMinutes % 60) : String.format("%s小时%s分钟", hour, durationMinutes % 60));

                dto.setWarnDesc(String.format("人员'%s'在%s触发了%s预警，距当前%s", dto.getPersonName()
                        , DateUtils.format(dto.getAlarmTime(), DateUtils.FormatType.COMMON)
                        ,PreWarnConstants.AlarmTypeEnum.getDescByType(dto.getPreWarnType())
                        , dto.getDiffValue()));
            }

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return preWarningRecordDao.queryTotal(params);
    }

    @Override
    public Long save(PreWarningRecordDto dto) {
        PreWarningRecordEntity entity = CopyUtils.copyObj(dto, PreWarningRecordEntity.class);
        entity.setId(Snowflake.nextId());
        preWarningRecordDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PreWarningRecordDto dto) {
        PreWarningRecordEntity entity = CopyUtils.copyObj(dto, PreWarningRecordEntity.class);
        preWarningRecordDao.updateById(entity);
        CacheKit.invalidRedisCache(PRE_WARNING_RECORD_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void updateAllColumnById(PreWarningRecordDto dto) {
        PreWarningRecordEntity entity = CopyUtils.copyObj(dto, PreWarningRecordEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, preWarningRecordDao);

        CacheKit.invalidRedisCache(PRE_WARNING_RECORD_CACHE_BY_ID + dto.getId());
    }

    @Override
    public void deleteById(Long id) {
        preWarningRecordDao.deleteById(id);

        CacheKit.invalidRedisCache(PRE_WARNING_RECORD_CACHE_BY_ID + id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
